package com.coding365.rpcprovider.proxy;

import com.lagou.entity.RpcRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class JdkDynamicProxy {

    @Autowired
    private ApplicationContext applicationContext;

    public Object doProxy(RpcRequest rpcRequest){
        try {

            String className = rpcRequest.getClassName();
            String methodName = rpcRequest.getMethodName();
            Object[] parameters = rpcRequest.getParameters();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();

            Class<?> aClass = Class.forName(className);
            Object o = applicationContext.getBean(aClass);
            Method method = aClass.getMethod(methodName, parameterTypes);
            Object returnObj = method.invoke(o,parameters);

            rpcRequest.setRetureObject(returnObj);


        }catch (Exception e){
            rpcRequest.setRetureObject("fail");
        }

        return rpcRequest;

    }

}
